package com.aiju.common.download;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @version V1.0
 * @FileName: com.app.john.updata.DefaultDownLoader.java
 * @author: 佐为
 * @date: 2016-09-27 15:23
 * @Description
 */
public class DefaultDownLoader implements Downloader {

    private ExecutorService mExecutor;

    private OnDownloaderListener mOnDownloaderListener;

    public DefaultDownLoader() {
        mExecutor = Executors.newSingleThreadExecutor();
    }

    @Override
    public void setListener(OnDownloaderListener downloaderListener) {
        this.mOnDownloaderListener = downloaderListener;
    }

    @Override
    public void download(final String url, final String filePath, long size) {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                httpDownload(url, filePath);
            }
        });
    }

    @Override
    public void cancelDownload() {
        mExecutor.shutdownNow();
    }

    private void httpDownload(String urlString, String filePath) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                if (mOnDownloaderListener != null) {
                    mOnDownloaderListener.onFailure(connection.getResponseCode(), "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage());
                }
            }
            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();
            // download the file
            input = connection.getInputStream();
            output = new FileOutputStream(filePath);
            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    //return null;
                }
                total += count;
                // publishing the progress....
                if (fileLength > 0) {
                    mOnDownloaderListener.onDownloadProgress((int) (total * 100 / fileLength));
                } // only if total length is known
                //publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            if (mOnDownloaderListener != null) {
                mOnDownloaderListener.onFailure(404, e.getMessage());
            }
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }
            if (connection != null)
                connection.disconnect();
        }
        if (mOnDownloaderListener != null) {
            mOnDownloaderListener.onDownloadFinsh(filePath);
        }
    }

    private boolean isCancelled() {
        return false;
    }
}
